﻿using System;
using System.IO;

namespace HttpCrawler.Engine
{
    public class FileSystemHttpCrawlerContentPersister : IHttpCrawlerContentPersister
    {
        private readonly string _OutputPath;

        private readonly string _DefaultFileName;

        public FileSystemHttpCrawlerContentPersister(string outputPath, string defaultFileName)
        {
            if (string.IsNullOrWhiteSpace(outputPath))
            {
                throw new ArgumentNullException("outputPath");
            }

            if (string.IsNullOrWhiteSpace(defaultFileName))
            {
                throw new ArgumentNullException("defaultFileName");
            }

            _OutputPath = outputPath;
            _DefaultFileName = defaultFileName;
        }

        public void PersistContent(HttpCrawlerContent content)
        {
            if (content == null)
            {
                return;
            }

            var destinationFilePath = GetDestinationFilePath(content);

            using (var fs = File.Open(destinationFilePath, FileMode.OpenOrCreate))
            {
                content.Save(fs);
            }
        }

        private string GetDestinationFilePath(HttpCrawlerContent content)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            var fileDirectory = UriHelper.ToFilePath(new Uri(content.ResponseUrl.GetComponents(UriComponents.Path | UriComponents.HostAndPort, UriFormat.Unescaped).Replace(":", "_")));
            var destinationFilePath = Path.Combine(_OutputPath, fileDirectory);

            if (!Path.HasExtension(destinationFilePath))
            {
                // assume directory and append default file name
                destinationFilePath = Path.Combine(destinationFilePath, _DefaultFileName);
            }

            PathHelper.CreateMissingDirectories(destinationFilePath);

            return destinationFilePath;
        }
    }
}
